package com.ternnetwork.core.dao.impl.org;


import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import com.ternnetwork.core.dao.org.OrganizationUserRelationshipDao;
import com.ternnetwork.core.entity.User;
import com.ternnetwork.core.entity.org.OrganizationUserRelationship;
import com.ternnetwork.core.entity.org.OrganizationUserRelationshipId;
import com.ternnetwork.persistence.dao.impl.IBaseDaoImpl;

@Repository("organizationUserRelationshipDao")
public class OrganizationUserRelationshipDaoImpl extends IBaseDaoImpl<OrganizationUserRelationship>implements OrganizationUserRelationshipDao {

	@Override
	public OrganizationUserRelationship findById(OrganizationUserRelationshipId id){
		return findById(OrganizationUserRelationship.class, id);
	}
	@Override
	public void save(User user,String organizationIds,String deleteOrganizationIds){
		
		String[] organizationIdArray=StringUtils.isEmpty(organizationIds)==true?new String[]{}:organizationIds.split(",");
		
		for(String organizationId:organizationIdArray){
			OrganizationUserRelationshipId id=new OrganizationUserRelationshipId(user.getId(), Long.parseLong(organizationId));
			OrganizationUserRelationship organizationUserRelationship=findById(id);
			if(organizationUserRelationship==null){
				organizationUserRelationship=new OrganizationUserRelationship();
				organizationUserRelationship.setId(id);
				persist(organizationUserRelationship);
			}
		}
		
		String[] deleteOrganizationArray=StringUtils.isEmpty(deleteOrganizationIds)==true?new String[]{}:deleteOrganizationIds.split(",");
		for(String organizationId:deleteOrganizationArray){
			OrganizationUserRelationshipId id=new OrganizationUserRelationshipId(user.getId(), Long.parseLong(organizationId));
			OrganizationUserRelationship organizationUserRelationship=findById(id);
			if(organizationUserRelationship!=null){
				user.getOrganizationUserRelationshipes().remove(organizationUserRelationship);
				delete(organizationUserRelationship);
			}
		}
		
	}
	@Override
	public void delete(long organizationId){
		bulkUpdate("delete from OrganizationUserRelationship  where organization.id=?1", organizationId);
	}
	@Override
	public List<OrganizationUserRelationship> findAll(long userId){
		return findAll("from OrganizationUserRelationship where  user.id=?1", userId);
	}
	
	
	
	
	
	
}
